<?php
declare(strict_types=1);

namespace cms\system\service;

use Hyperf\Config\Config;
use Hyperf\Database\Model\ModelNotFoundException;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;
use Symfony\Component\Finder\Finder;

abstract class AbstractService
{
    public function readSetting(string $name = '', string $module = ''): Config
    {
        $setting = [];
        $module = $module ?: self::getRequestModuleName();
        $settingPath = BASE_PATH . '/cms/' . $module . '/setting/';
        if (!$name) {
            $finder = new Finder();
            $finder->files()->in($settingPath)->name('*.php');
            foreach ($finder as $file) {
                $setting[$file->getBasename('.php')] = require $file->getRealPath();
            }
        } else {
            $settingPath .= $name . '.php';
            if (file_exists($settingPath) && is_readable($settingPath)) {
                $setting = require $settingPath;
            }
            $setting = is_array($setting) ? $setting : [];
        }
        return new Config($setting);
    }

    public function getRequestModuleName()
    {
        $callback = self::getRequestCallback();
        // 命名空间
        $namespace = $callback[0];
        $namespace_array = explode('\\', $namespace);
        return $namespace_array[1];
    }

    /**
     * 获取请求回调
     * @return mixed
     */
    public function getRequestCallback()
    {
        $request = ApplicationContext::getContainer()->get(RequestInterface::class);
        return ($request->getAttribute('Hyperf\\HttpServer\\Router\\Dispatched'))->handler->callback;
    }

    public function getDataById(int $id, bool $force = false)
    {
        if (!$id) {
            if ($force) {
                throw new ModelNotFoundException('参数错误');
            }
            return null;
        }
        $data = $this->model->where([
            ['id', '=', $id]
        ])->first();
        if (!$data && $force) {
            throw new ModelNotFoundException('参数错误');
        }
        return $data;
    }
}